var currProjectId = "",currProjectName="";
layui.config({
    base: '../lib/layui/lay/modules/',
}).use(['element','table','form','layer','tree', 'util','customSelect'], function(){
    var table = layui.table,
        form = layui.form,
        $ = layui.jquery,
        layer = layui.layer;
    var tree = layui.tree;

    form.verify({
        cardNum: function(value, item){
            var len = item.getAttribute('lay-leng');
            if(value.length != len){
                return '卡号必须是8位';
            }
        }
    });

    const select = layui.customSelect;
    $.get('/cardpassmgrProject/listAll',{},function (res) {
        if(res.status === 200){
            var options = res.data;
            tree.render({
                elem: '#projectTree'
                ,data: options
                ,edit: ['add', 'update', 'del'] //操作节点的图标
                ,click: function(obj){
                    currProjectId= obj.data.id;
                    currProjectName= obj.data.title;
                    queryCard();
                },operate: function(obj){
                    var type = obj.type; //得到操作类型：add、edit、del
                    var data = obj.data; //得到当前节点的数据
                    var elem = obj.elem; //得到当前节点元素
                    //Ajax 操作
                    var id = data.id; //得到节点索引
                    if(type === 'add'){ //增加节点
                        //返回 key 值
                        var newId = new Date().getTime();
                        var param = {id:newId,name:"未命名",parentId:id,isUpdate:false};
                        var success = ajaxPost('/cardpassmgrProject/saveOrUpdate',param);
                        if(!success){
                            return false;
                        }
                        return id;
                    } else if(type === 'update'){ //修改节点
                        //得到修改后的内容
                        var newTitle = elem.find('.layui-tree-txt').html();
                        var param = {id:id,name:newTitle,isUpdate:true};
                        ajaxPost('/cardpassmgrProject/saveOrUpdate',param);
                    } else if(type === 'del'){ //删除节点
                        var param = {id:id};
                        ajaxPost('/cardpassmgrProject/delete',param);
                    }
                }
            });
            select.render({
                el: 'project',
                data: options,
                type: 'radio',
                checkbox: true,
                checked: function (obj) {
                    var title = obj.combData.values;
                    var id = obj.combData.idents;
                    console.log(title);
                    $("#projectId").val(id);
                }
            });
        }
    });
    //添加卡片信息
    addCard = function () {
        $("#resource_form")[0].reset();
        $("#addCardForm").attr("disabled", false);
        $("#addCardForm").attr("class", "layui-btn");
        $('#id').val("");
        $('#projectId').val("");
        $("#addCardForm").show();
        layer.open({
            type: 1
            , title: '卡片添加'
            , shadeClose: true
            , area: ['60%', '99%']
            , content: $('#addCardDiv')
        });
    };

    loadDictList('carType');

    function loadDictList(dictType) {
        $.get('/cardpassmgrCard/getDictItems', {dictType:dictType}, function (result) {
            if(result != null){
                if(result.data != null){
                    var a$opt_html = "<option value=''>全部</option>";
                    var $opt_html = "<option value=''>请选择车辆类型</option>";
                    $.each(result.data, function (index, item) {
                        a$opt_html += "<option value='" + item.dictKey + "'>" + item.dictName + "</option>";
                        $opt_html += "<option value='" + item.dictKey + "'>" + item.dictName + "</option>";
                    });
                    $("#searchTypeId").empty().append(a$opt_html);
                    $("#typeId").empty().append($opt_html);
                    form.render('select');
                }
            }
        });
    }
    loadDictList2("ghdw","请选择供货单位","ghdwId");
    loadDictList2("cydw","请选择承运单位","cydwId");
    loadDictList2("gywl","请选择物料单位","gywlId");
    loadDictList3("wlgg","请选择物料规格","wlgg");
    loadDictList3("cfdd","请选择存放地点","cfdd");

    function loadDictList2(dictType,tip,selectId) {
        $.get('/cardpassmgrCard/getDictItems', {dictType:dictType}, function (result) {
            if(result != null){
                if(result.data != null){
                    var $opt_html = "<option value=''>"+tip+"</option>";
                    $.each(result.data, function (index, item) {
                        $opt_html += "<option value='" + item.dictKey + "'>" + item.dictName + "</option>";
                    });
                    $("#"+selectId).empty().append($opt_html);
                    form.render('select');
                }
            }
        });
    }

    function loadDictList3(dictType,tip,selectId) {
        $.get('/cardpassmgrCard/getDictItems', {dictType:dictType}, function (result) {
            if(result != null){
                if(result.data != null){
                    var $opt_html = "<option value=''>"+tip+"</option>";
                    $.each(result.data, function (index, item) {
                        $opt_html += "<option value='" + item.dictName + "'>" + item.dictName + "</option>";
                    });
                    $("#"+selectId).empty().append($opt_html);
                    form.render('select');
                }
            }
        });
    }

    //初始数据
    var data1 = [{
            title: '默认自定义项'
            ,id: '1'
            ,parentId: "0"
            ,children: [{
                title: '子项1'
                ,id: '1001'
            },{
                title: '子项2'
                ,id: '1002'
            },{
                title: '子项3'
                ,id: '1003'
            }]
        }]

    function ajaxPost(url,param){
        $.post(url,param,function (res) {
            if(res.status === 200){
                layer.msg(res.msg,{});
                return true;
            }else{
                layer.msg(res.msg);
                return false;
            }
        });
    }

    loadCardTable("");
    function loadCardTable(projectId) {
        table.render({
            elem: '#cardTable'
            ,url:'/cardpassmgrCard/list'
            ,title: '卡片管理'
            ,where: {'projectId': projectId}
            ,cols: [[
                {field: 'xh',type:'numbers', title: '序号',}
                ,{type:'checkbox'}
                ,{field:'cardNum', title:'通行卡号',align:'center'}
                ,{field:'type', title:'车辆类型',align:'center'}
                ,{field:'carNum', title:'车牌号',align:'center'}
                ,{field:'principal', title:'负责人员',align:'center'}
                ,{field:'right',title:'操作',toolbar:'#barOperate',align:'center'}
            ]]
            ,page: true
        });
    }

    table.on('tool(cardTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'edit':
                $("#update_form").attr("disabled", false);
                $("#update_form").attr("class", "layui-btn");
                renderForm(data);
                $("#addCardForm").show();
                $("#cancel_form").show();
                form.render();
                layer.open({
                    type: 1
                    , title: '编辑卡片'
                    , shadeClose: true
                    , area: ['60%', '80%']
                    , content: $('#addCardDiv')
                });
                break;
            case 'detail':
                renderForm(data);
                $("#addCardForm").hide();
                $("#cancel_form").hide();
                form.render();
                layer.open({
                    type: 1
                    , title: '卡片详情'
                    , shadeClose: true
                    , area: ['60%', '80%']
                    , content: $('#addCardDiv')
                });
                break;
            case 'delete':
                layer.confirm('确定要删除吗?', {
                }, function(){
                    layer.load();
                    $.get('/cardpassmgrCard/delete',{id:data.id},function (res) {
                        layer.msg(res.msg,{
                            time:500,
                            end:function () {
                                queryCard();
                                layer.closeAll();
                            }
                        });
                    });
                });
                break;

        }
    });

    function renderForm(data){
        $("#id").val(data.id);
        $("#projectId").val(data.projectId);
        $("#project").val(data.project);
        $("#cardNum").val(data.cardNum);
        $("#typeId").val(data.typeId);
        $("#carNum").val(data.carNum);
        $("#principal").val(data.principal);
        $("#phone").val(data.phone);
        $("#ghdwId").val(data.ghdwId);
        $("#cydwId").val(data.cydwId);
        $("#gywlId").val(data.gywlId);
        $("#wlgg").val(data.wlgg);
        $("#mrkl").val(data.mrkl);
        $("#remark").val(data.remark);
    }

    function queryCard(){
        var cardNum = $("#searcheCardNum").val();
        var typeId = $("#searchTypeId").val();
        var carNum = $("#searcheCarNum").val();
        var principal = $("#searchePrincipal").val();
        table.reload('cardTable',{
            where: {projectId:currProjectId,cardNum:cardNum,typeId:typeId,carNum:carNum,principal:principal}
            ,page:  {
                curr:1
            }
        });
    }

    form.on('submit(queryCard)',function () {
        queryCard();
        return false;
    });

    form.on('submit(addCardForm)',function(data){
        var project = $("#project").val();
        if(!project){
            layer.msg("请选择项目",{icon:5});
            return false;
        }
        $("#addCardForm").attr("disabled", true);
        $("#addCardForm").attr("class", "layui-btn layui-btn-disabled");
        data.field.type = $("#typeId").find("option:selected").text();
        data.field.ghdw = $("#ghdwId").find("option:selected").text();
        data.field.cydw = $("#cydwId").find("option:selected").text();
        data.field.gywl = $("#gywlId").find("option:selected").text();
        layer.load();
        $.ajax({
            type: 'post',
            url: '/cardpassmgrCard/saveOrUpdate',
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(data.field),
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function (){
                    layer.closeAll();
                },1000);
                $("#addCardForm").attr("disabled", false);
                $("#addCardForm").attr("class", "layui-btn");
                table.reload('cardTable');
            },
        });
        return false;
    });

    form.on('submit(config_form)',function(data){
        $("#config_form").attr("disabled", true);
        $("#config_form").attr("class", "layui-btn layui-btn-disabled");
        var actlived =  $("#actlive").prop("checked");
        data.field.actlive = actlived ? 1 : 0;
        layer.load();
        $.ajax({
            type: 'post',
            url: '/qzsqDevice/saveOrUpdate',
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(data.field),
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function (){
                    layer.closeAll();
                },1000);
                $("#config_form").attr("disabled", false);
                $("#config_form").attr("class", "layui-btn");
                table.reload('cardTable');
            },
        });
        return false;
    });


    // 批量删除
    form.on('submit(batchDelete)',function(obj){
        var checkStatus = table.checkStatus('cardTable');
        var	data = checkStatus.data;
        if(data.length === 0){
            layer.tips("请至少选择一条记录!",this);
            return false;
        }
        var idArr = [];
        data.forEach(item=>{
            idArr.push(item.id);
        });
        var rIds = JSON.stringify(idArr);
        var params = {params:JSON.stringify({"rIds":rIds})};
        layer.confirm('确定要删除选择的记录么',function(){
            $.post('/cardpassmgrCard/deleteAll',params,function (res) {
                if(res.status === 200){
                    layer.msg(res.msg,{});
                    queryCard();
                }else{
                    layer.msg(res.msg);
                }
            });
        });
        return false;
    });

    // 导入
    $("#batchImport").on('click', function (){
        if(!currProjectId){
            layer.msg("请选择项目");
            return false;
        }
        layer.open({
            type: 1
            ,title: '上传文件'
            ,area: ['45%','30%']
            ,content: $('#upload')
        });
    });

    // 下载模板
    $("#down_user_template").on('click', function (){
        $('#downButton')[0].click();
    });
    //提交导入信息
    form.on('submit(upload_form)',function(){
        $("#upload_form").attr("disabled", true);
        $("#upload_form").attr("class", "layui-btn layui-btn-disabled");
        var formData = new FormData();
        formData.append("file",$("#uploadExcel")[0].files[0]);
        formData.append("projectId",currProjectId);
        formData.append("projectName",currProjectName);
        layer.load();
        $.ajax({
            url:'/cardpassmgrCard/uploadCard',
            type: 'POST',
            data: formData,
            processData: false,
            contentType:false,
            success:function(res){
                if (res.resultCode === "000") {
                    queryCard();
                    layer.msg(res.resultDesc,{icon: 1});
                }else {
                    layer.msg(res.resultDesc,{
                        time: 5000,
                    })
                }
                setTimeout(function () {
                    layer.closeAll();
                },1000);
                $("#uploadExcel").val("");
                $("#file_name").val("");
                $("#upload_form").attr("disabled", false);
                $("#upload_form").attr("class", "layui-btn");
            }

        });
        return false;
    });

    $("#uploadProductBtn").on("click",function(){
        $("#uploadExcel").click();
    });
    $("#uploadExcel").on("change",function(){
        var name = $("#uploadExcel").val();
        var fileType = name.substring(name.lastIndexOf(".")+1);
        if(fileType !== "xls" && fileType !== "xlsx"){
            layer.msg("亲，请选择正确的excel格式哦!",{icon:5});
            $("#upload_form").attr("disabled", true);
            $("#upload_form").addClass("layui-btn-disabled");
        }else {
            $("#upload_form").attr("disabled", false);
            $("#upload_form").removeClass("layui-btn-disabled");
            var index = name.lastIndexOf("\\")+1;
            $("#file_name").val(name.substring(index));
        }
    });

    $("#cancel_form").on('click',function (){
        layer.closeAll();
        return false;
    });

    $("#syncDevice").on('click', function (){
        layer.confirm('同步数据，是否继续？', {
            btn: ['确认', '取消'] //按钮
        }, function () {
            var index = layer.load(2, {
                shade: [0.4, '#000'],
                content: '同步中...',
                success: function (layero) {
                    layero.find('.layui-layer-content').css({
                        'padding-top': '40px',
                        'width': '200px'
                    });
                }
            });
            $.post('/qzsqDevice/syncData',{},function (res) {
                if(res.status === 200){
                    layer.msg(res.msg,{
                        time:1000,
                        end:function () {
                            reload();
                        }
                    });
                }else{
                    layer.msg(res.msg);
                }
                layer.close(index);
            });
        });
    });

});

function reload(){
    location.reload();
}
